# -*- coding: utf-8 -*-
# @Author: Administrator
# @Date:   2022-11-10 10:05:27
# @Last Modified by:   Administrator
# @Last Modified time: 2022-11-10 15:10:14
import time
import json
import requests
import os
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.config import *
from controllers.common import *
from controllers.db import *

index_data_api = Blueprint('index_data_api', __name__)
remark_delete_api = Blueprint('remark_delete_api', __name__)
clone_data_api = Blueprint('clone_data_api', __name__)


# 首页数据
# 参数 event_type
@index_data_api.route('/index_data', methods=['POST'])
def index_data():
    params = json.loads(request.data)
    event_type = params['event_type']

    block_db_data = get_block_pid(event_type)
    db_data = get_project_data(event_type, -1)
    new_data = []
    for node in db_data:
        append_obj = {"project": node['project'], "remark": node['remark']}
        # Add title in query.localization
        if event_type in [63, 1009, 999, 1008, 1007]:
            append_obj['title'] = 'Unknown Title'

            localization = json.loads(node['localization'])
            if '1' in localization:
                if 'title' in localization['1']:
                    append_obj['title'] = localization['1']['title']
        if event_type in [999]:
            basic = json.loads(node['basic'])
            append_obj['event_ui'] = basic['event_ui']
        new_data.append(append_obj)

    result_data = {
        'status': 200,
        'data': {
            'msg': '',
            'ret': 0,
            'type': 'success',
            'env': EVN,
            'item': {
                'project_data': new_data,
                'block_data': block_db_data
            }
        }
    }
    return jsonify(result_data)


@remark_delete_api.route('/remark_delete_data', methods=['POST'])
def remark_delete_data():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    event_type = params['event_type']

    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    db_name = get_db_name(event_type)

    if _action == 'remark':
        _data = params['remark'].strip()
        eval(db_name).query.filter_by(project=_project).update({'remark': _data})
        db.session.commit()
    elif _action == 'delete':
        db_data = eval(db_name).query.filter_by(project=_project).first()
        db.session.delete(db_data)
        db.session.commit()
        new_db_data = eval(db_name).query.filter_by(project=_project).first()
        if new_db_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
    else:
        result_data['status'] = 500
        result_data['data']['msg'] = "操作异常"

    return jsonify(result_data)


# 参数：{"pid":[-1表示默认克隆]}
@clone_data_api.route('/clone_data_api', methods=['POST'])
def clone_data():
    params = json.loads(request.data)

    event_type = params['event_type']
    block_id = params['block_id']
    clone_pid_list = params['data_list']

    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': {}}}

    for pid, plist in clone_pid_list.items():
        for p in plist:
            if p == -1:
                target_pid = get_max_pid(event_type, block_id) + 1
            else:
                target_pid = p

            clone_data(event_type, int(pid), target_pid)
            update_max_pid(event_type, block_id, target_pid)

            if pid not in result_data['data']['item']:
                result_data['data']['item'][pid] = []

            result_data['data']['item'][pid].append(target_pid)

    return jsonify(result_data)


def get_project_data(event_type, project):
    db_name = get_db_name(event_type)
    if int(project) == -1:
        db_data = eval(db_name).query.order_by('project').all()
    else:
        db_data = eval(db_name).query.filter_by(project=project).order_by('project').all()
    return to_json(db_data)


def clone_data(event_type, raw_pid, target_pid):
    db_name = get_db_name(event_type)

    raw_data = get_project_data(event_type, raw_pid)
    raw_data[0]['project'] = target_pid

    target_data = eval(db_name).query.filter_by(project=target_pid).first()
    if target_data is not None:
        db.session.delete(target_data)

    new_project_data = eval(db_name)(**raw_data[0])
    db.session.add(new_project_data)
    db.session.commit()

    result_data = eval(db_name).query.filter_by(project=target_pid).first()
    if result_data is not None:
        return True
    else:
        return False


def get_event_config():
    with open(STATIC_PATH + 'event_config.json', encoding='utf8') as f:
        data = json.load(f)
    return data


def get_db_name(event_type):
    event_config = get_event_config()
    db_name = event_config[str(event_type)]['db_name']
    return db_name


def get_block_pid(event_type):
    result = []
    db_data = PidBlcok.query.filter_by(event_type=event_type).order_by('block_id').all()
    for node in to_json(db_data):
        begin_pid = node['begin_pid']
        end_pid = node['end_pid']
        cur_max_pid = node['cur_max_pid']
        block_id = node['block_id']
        name = node['name']

        result.append({
            "cur_max_pid": cur_max_pid,
            "pid_range": [begin_pid, end_pid],
            "name": name,
            "block_id": block_id
        })

    return result


def get_max_pid(event_type, block_id):
    result = get_block_pid(event_type)
    for i in result:
        if i['block_id'] == block_id:
            return i['cur_max_pid']


def update_max_pid(event_type, block_id, max_id):
    # cur_max_pid = get_max_pid(event_type, block_id)

    block_data = PidBlcok.query.filter_by(event_type=event_type).all()
    for block in block_data:
        if block.begin_pid <= max_id <= block.end_pid and max_id > block.cur_max_pid:
            block.cur_max_pid = max_id
    db.session.commit()
    return True


def to_json(all_vendors):
    v = [ven.to_dict() for ven in all_vendors]
    return v
